const validate = require("validate.js");
const moment = require("moment");
// 扩展验证器
// 判断是否存在
validate.validators.exist = function (value, options) {
  // console.log(value, options);
  const { validator } = options;
  if (!validator) {
    throw new Error(
      "To implement a custom validator exist in Validate.js, ensuring that the validator property in options is requierd"
    );
  } else {
    return validator(value);
  }
};

// 增强验证器
validate.extend(validate.validators.datetime, {
  /**
   * 将任意格式的时间解析成验证器可以识别格式
   * @param {*} value datetime验证器传入的时间
   * @param {*} options datetime验证器传入的配置
   * @returns 时间戳
   */
  parse: function (value, options) {
    let format = ["YYYY-MM-DD hh:mm:ss", "YYYY-M-D h:m:s", "x"];
    if (options.dateOnly) {
      format = ["YYYY-MM-DD", "YYYY-M-D", "x"];
    }
    return +moment.utc(value, format, true);
  },
  format: function (value, options) {
    let format = "YYYY-MM-DD hh:mm:ss";
    if (options.dateOnly) {
      format = "YYYY-MM-DD";
    }
    return moment.utc(value).format(format);
  },
});
